package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.GroupNameIDCache;
import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.cache.URILabelCache;
import cn.edu.nju.ws.sview.cache.URITypeCache;
import cn.edu.nju.ws.sview.cache.UserNameIDCache;
import cn.edu.nju.ws.sview.crawler.Crawler;
import cn.edu.nju.ws.sview.crawler.Element;
import cn.edu.nju.ws.sview.database.DBOperations;
import cn.edu.nju.ws.sview.rdf.ResourceFactory;
import cn.edu.nju.ws.sview.rdf.URIResource;
import cn.edu.nju.ws.sview.util.PropertyList;
import cn.edu.nju.ws.sview.util.URIUtil;
import cn.edu.nju.ws.sview.views.Bookmark;
import cn.edu.nju.ws.sview.views.Collaboration;
import cn.edu.nju.ws.sview.views.Comment;
import cn.edu.nju.ws.sview.views.CustomCollection;
import cn.edu.nju.ws.sview.views.CustomEntity;
import cn.edu.nju.ws.sview.views.Entity;
import cn.edu.nju.ws.sview.views.Image;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;
import cn.edu.nju.ws.sview.views.data.EntityManagement;
import cn.edu.nju.ws.sview.views.data.EntityManagement.Item;
import cn.edu.nju.ws.sview.views.data.EntityManagement.RecomdItem;
import cn.edu.nju.ws.sview.views.data.EntityManagement.URIMember;

/**
 * Servlet implementation class Entity
 */
@WebServlet("/EntityServlet")
public class EntityServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String STATUS_CONFLICT = "conflict";
	public static final String STATUS_OK = "ok";
	public static final String STATUS_REMOVE = "removed";
	public static final String STATUS_NOAUTHORITY="noauthority";
	public static final String STATUS_MEMBER_CONFLICT="memconflict";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EntityServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String option = null;
		String json = null;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		if (request.getParameter("entity") != null) {
			json = request.getParameter("entity");
			option = "entity";
		} else if (request.getParameter("hint") != null) {
			json = request.getParameter("hint");
			option = "hint";
		} else if (request.getParameter("label") != null) {
			json = request.getParameter("label");
			option = "label";
		} else if (request.getParameter("gmem") != null) {
			json = request.getParameter("gmem");
			option = "gmem";
		} 
		else if (request.getParameter("recommendCorefEntity") != null) {
				json = request.getParameter("recommendCorefEntity");
				option = "recommendCorefEntity";
		} 
		else if (request.getParameter("falconSearchEntity") != null) {
			json = request.getParameter("falconSearchEntity");
			option = "falconSearchEntity";
	   } 
		else if (request.getParameter("checkmemURI") != null) {
			json = request.getParameter("checkmemURI");
			option = "checkmemURI";
		}
		else if (request.getParameter("sventity") != null) {
			json = request.getParameter("sventity");
			option = "sventity";
		}
		else if (request.getParameter("hasRDFDesc") != null) {
			json = request.getParameter("hasRDFDesc");
			option = "hasRDFDesc";
		}		
		if (option.equals("entity")) {
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String type = (String) regtJSON.get("type");
			String lang = (String) regtJSON.get("lang");
			int start = ((Long) regtJSON.get("start")).intValue();
			int length = ((Long) regtJSON.get("length")).intValue();
			ArrayList<QuadItem> array = new ArrayList<QuadItem>();
			boolean hasMoreElements = true;
			if (type.equals("popAll")) {
				hasMoreElements = EntityBrowsing.fetchAll(start, length, lang,
						array);
			} else if (type.equals("mineAll")) {
				String user = (String) regtJSON.get("user");
				hasMoreElements = EntityBrowsing.fetchUserAll(user, start,
						length, lang, array);
			} else if (type.equals("popEntity")) {
				hasMoreElements = EntityBrowsing.fetchEntities(start, length,
						lang, array);
			} else if (type.equals("popCollection")) {
				hasMoreElements = EntityBrowsing.fetchCollections(start,
						length, lang, array);
			} else if (type.equals("mineEntity")) {
				String user = (String) regtJSON.get("user");
				hasMoreElements = EntityBrowsing.fetchUserEntities(user, start,
						length, lang, array);
			} else if (type.equals("mineCollection")) {
				String user = (String) regtJSON.get("user");
				hasMoreElements = EntityBrowsing.fetchUserCollection(user,
						start, length, lang, array);
			}
			JSONArray elements = new JSONArray();
			for (QuadItem item : array) {
				JSONObject jsob = new JSONObject();
				jsob.put("genre", item.getGenre());
				jsob.put("id", item.getId());
				String name = item.getName();
				if (item.getGenre() == Entity.URI_ENTITY && name.equals("")) {
					if (lang.equals("en")) {
						try {
							name = URIUtil.getLocalname(URIIDCache
									.getInstance().getURI(item.getId()));
						} catch (Throwable e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						continue;
					}

				}
				jsob.put("name", name);
				JSONArray types = new JSONArray();
				ArrayList<Entry<Integer, String>> typeArray = item.getTypes();
				for (Entry<Integer, String> mapItem : typeArray) {
					JSONObject tob = new JSONObject();
					tob.put("label", mapItem.getValue());
					tob.put("type_id", mapItem.getKey());
					types.add(tob);
				}
				jsob.put("type", types);
				elements.add(jsob);
			}
			JSONObject result = new JSONObject();
			result.put("result", elements);
			result.put("hasMore", hasMoreElements);
			response.getWriter().print(result);
		} else if (option.equals("hint")) {
			/**** !!!in the future need to add origin entities!!! **/
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String kw = (String) regtJSON.get("kw");
			String lang = (String) regtJSON.get("lang");
			String userName = (String) regtJSON.get("userName");
			ArrayList<QuadItem> array = null;
			array = EntityBrowsing.kw2Entity(kw, lang,userName);

			JSONArray elements = new JSONArray();
			for (QuadItem item : array) {
				JSONObject jsob = new JSONObject();
				jsob.put("genre", item.getGenre());
				jsob.put("id", item.getId());
				jsob.put("name", item.getName());
				jsob.put("lang", item.getLang());
				JSONArray types = new JSONArray();
				ArrayList<Entry<Integer, String>> typeArray = item.getTypes();
				for (Entry<Integer, String> mapItem : typeArray) {
					types.add(mapItem.getValue());
				}
				jsob.put("type", types);
				elements.add(jsob);
			}
			JSONObject result = new JSONObject();
			result.put("result", elements);
			response.getWriter().print(result);
		} else if (option.equals("label")) {
			URLDecoder coder = new URLDecoder();
			String str = coder.decode(json);
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String lang = (String) regtJSON.get("lang");
			int uri_id = ((Long) regtJSON.get("uri_id")).intValue();

			String label = "";
			try {
				/* must update the label */
				label = URILabelCache.getInstance().updateLabel(uri_id, lang);
				if (label.equals("")) {
					/* check whether the class uri is dereferenced */
					if (DBOperations.getValidStatus(uri_id) == URIResource.NOT_PINGED) {
						URIResource uriRes = ResourceFactory.getInstance()
								.createURIResource(
										URIIDCache.getInstance()
												.getURI(uri_id));
						Crawler.getInstance().submitURI(uriRes);
						Crawler.getInstance().promoteWeight(uriRes,
								Element.LEVEL_1);
						/* wait for the download finish */
						while (Crawler.getInstance().checkStatus(uriRes) != Crawler.STATUS_DONE) {
							Thread.sleep(100);
						}
						label = URILabelCache.getInstance().updateLabel(
								uri_id, lang);
					}
				}
				if (label.equals("") && lang.equals("en")) {
					label = URIUtil.getLocalname(URIIDCache.getInstance()
							.getURI(uri_id));
				}
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			response.getWriter().print(label);
		} else if (option.equals("gmem")) {
			//get uri members of the entity
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			int etype = Integer.parseInt((String) regtJSON.get("etype"));
			int eid = Integer.parseInt((String) regtJSON.get("eid"));
			String lang = (String) regtJSON.get("lang");
			String isCollection = (String) regtJSON.get("isCollection");
			
			JSONArray result = new JSONArray();
			if (eid > 0) {
				ArrayList<URIMember> members = EntityManagement
						.getInstance().getIdentityMembers(etype, eid, lang);

				for (URIMember entry : members) {
					JSONObject jsob = new JSONObject();
					jsob.put("uriID", entry.getURIID());
					jsob.put("label", entry.getLabel());
					jsob.put("uri", entry.getURI());
					result.add(jsob);
				}
			}else  if(eid<0){
				int setype = Integer.parseInt((String) regtJSON.get("s_etype"));
				int seid = Integer.parseInt((String) regtJSON.get("s_eid"));
				int groupID = Integer.parseInt((String) regtJSON.get("groupID"));
				HashSet<Integer> set = new HashSet<Integer>();
				if(setype==Entity.URI_ENTITY){
					set.add(seid);
				}else{
					set.addAll(Entity.getMembersByEntityId(seid));
				}
				
				for (Integer uid : set) {
					int isExist = 0;
					
					if (isCollection == null) {

						HashSet<Item> items = EntityManagement.getInstance()
								.getRelatedMyGroupEntity(Entity.URI_ENTITY,
										uid, groupID, null);

						// =======
						if (items.size() > 0) {
							isExist = 1;
						}

						// ============
					}
					ArrayList<URIMember> members = EntityManagement
							.getInstance().getURIMembersOfEntity(Entity.URI_ENTITY,
									uid, lang);
					for (URIMember entry : members) {
						JSONObject jsob = new JSONObject();
						jsob.put("uriID", entry.getURIID());
						jsob.put("label", entry.getLabel());
						jsob.put("uri", entry.getURI());
						jsob.put("isExist", isExist);
						result.add(jsob);
					}
				}
			}
			response.getWriter().print(result);
		} 
		 else if (option.equals("recommendCorefEntity")) {
				String str = URLDecoder.decode(json,"utf-8");
				JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
				int etype = Integer.parseInt((String) regtJSON.get("etype"));
				int eid = Integer.parseInt((String) regtJSON.get("eid"));
				int groupID = Integer.parseInt((String) regtJSON.get("groupID"));
				int start = ((Long) regtJSON.get("start")).intValue();
				String lang = (String) regtJSON.get("lang");

				ArrayList<RecomdItem> recommends = new ArrayList<RecomdItem>();
				int totalNum = EntityManagement.getInstance()
						.getRecommendCorefEntity(etype, eid, groupID,lang,start,recommends);
				
				JSONArray items = new JSONArray();
				for (RecomdItem item : recommends) {
					int uriID = item.getURIID();
					String uri = null;
					try {
						uri = URIIDCache.getInstance().getURI(uriID);
					} catch (Throwable e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					String label = item.getLabel(lang) ;
					ArrayList<Entry<Integer, String>> typeArrayList =  URIResource.getTypesById(uriID, lang);
	                
					
					ArrayList<ArrayList<String>> snnipetArray = item.getSnippet();
					
					JSONObject jsob = new JSONObject();
					jsob.put("uriID", uriID);
					jsob.put("label", label);
					jsob.put("uri", uri);
					
				    JSONArray typeArray = new JSONArray();
				    for(Entry<Integer, String> entry:typeArrayList){
				    	JSONObject typeObject = new JSONObject();
				    	typeObject.put("id", entry.getKey());
				    	typeObject.put("label", entry.getValue()) ;
				    	typeArray.add(typeObject);
				    }
				    jsob.put("type", typeArray) ;
				    
				    JSONArray snippet = new JSONArray();
				    for(ArrayList<String> triple:snnipetArray){
				    	JSONArray snippetItem = new JSONArray();
				    	
				    	int pid = -1;
				    	for(int i=0;i<triple.size();i++){
				    		String mstr =triple.get(i);
				    		JSONObject obj = new JSONObject();
				    		
				    		ArrayList<String> itemStr = EntityManagement.getInstance().getSViewStr(mstr, lang);
				    		if(mstr.startsWith("u")){
				    			obj.put("type", "u");
				    			obj.put("id", Integer.valueOf(itemStr.get(0)));
				    			if(i==1)
				    				pid =  Integer.valueOf(itemStr.get(0));
				    			obj.put("uri",itemStr.get(1));
				    			obj.put("label", itemStr.get(2));
				    			
				    			//处理foaf:homepage等特殊属性
				    			HashSet<Integer> set = PropertyList.getDirectURIProperties();
				    			if(i==2&&set.contains(pid)){
				    				obj.put("directuri",1);
				    			}
				    		}else if(mstr.startsWith("l")){
				    			obj.put("type","l");
				    			obj.put("label",itemStr.get(0));
				    		}
				    		snippetItem.add(obj);
				    	}
				    	snippet.add(snippetItem);
				    }
				    
				    jsob.put("snippet", snippet);
					items.add(jsob);
				}
				
				JSONObject result = new JSONObject();
				result.put("items", items);
				result.put("totalNum", totalNum);
				response.getWriter().print(result);
		} 
		 else if (option.equals("falconSearchEntity")) {
				String str = URLDecoder.decode(json,"utf-8");
				JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
				String kw  =(String) regtJSON.get("kw");
				int start = ((Long) regtJSON.get("start")).intValue();
				String lang = (String) regtJSON.get("lang");

				ArrayList<RecomdItem> recommends = new ArrayList<RecomdItem>();
				int totalNum = EntityManagement.getInstance()
						.getFalconSearchEntity(kw, start, recommends);
				
				JSONArray items = new JSONArray();
				int pid = -1;
				for (RecomdItem item : recommends) {
					int uriID = item.getURIID();
					String uri = null;
					try {
						uri = URIIDCache.getInstance().getURI(uriID);
					} catch (Throwable e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					String label = item.getLabel(lang) ;
					ArrayList<Entry<Integer, String>> typeArrayList =  URIResource.getTypesById(uriID, lang);
	                
					
					ArrayList<ArrayList<String>> snnipetArray = item.getSnippet();
					
					JSONObject jsob = new JSONObject();
					jsob.put("uriID", uriID);
					jsob.put("label", label);
					jsob.put("uri", uri);
					
				    JSONArray typeArray = new JSONArray();
				    //由于falcons object search snippet多半有了type，因此这边不再显示
				    jsob.put("type", typeArray) ;
				    
				    JSONArray snippet = new JSONArray();
				    for(ArrayList<String> triple:snnipetArray){
				    	JSONArray snippetItem = new JSONArray();
				    	for(int i=0;i<triple.size();i++){
				    		String mstr = triple.get(i);
				    		JSONObject obj = new JSONObject();
				    		
				    		ArrayList<String> itemStr = EntityManagement.getInstance().getSViewStr(mstr, lang);
				    		if(mstr.startsWith("u")){
				    			obj.put("type", "u");
				    			obj.put("id", Integer.valueOf(itemStr.get(0)));
				    			if(i==1)
				    				pid =  Integer.valueOf(itemStr.get(0));
				    			obj.put("uri",itemStr.get(1));
				    			obj.put("label", itemStr.get(2));
				    			
				    			//处理foaf:homepage等特殊属性
				    			HashSet<Integer> set = PropertyList.getDirectURIProperties();
				    			if(i==2&&set.contains(pid)){
				    				obj.put("directuri",1);
				    			}
				    		}else if(mstr.startsWith("l")){
				    			obj.put("type","l");
				    			obj.put("label",itemStr.get(0));
				    		}
				    		snippetItem.add(obj);
				    	}
				    	snippet.add(snippetItem);
				    }
				    
				    jsob.put("snippet", snippet);
					items.add(jsob);
				}
				
				JSONObject result = new JSONObject();
				result.put("items", items);
				result.put("totalNum", totalNum);
				response.getWriter().print(result);
		} 		
		else if (option.equals("checkmemURI")) {
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			int groupID = Integer.parseInt((String) regtJSON.get("groupID"));
			String link = (String)regtJSON.get("link");
			String lang = (String)regtJSON.get("lang");
			String isCollection = (String)regtJSON.get("isCollection");
			
			int linkID = -1;
			try {
				linkID = URIIDCache.getInstance().getURIID(link, true);
			} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
			}
			
			JSONArray array = new  JSONArray();
			if (isCollection == null) {
				//对于集合不需要考虑成员冲突性
				HashSet<Item> entityArray = EntityManagement.getInstance()
						.getRelatedMyGroupEntity(Entity.URI_ENTITY, linkID,
								groupID, null);
				for (Item item : entityArray) {
					JSONObject jsob = new JSONObject();
					jsob.put("etype", item.getEType());
					jsob.put("eid", item.getEID());
					jsob.put("name", item.getName());
					array.add(jsob);
				}
			}
			
			JSONObject result = new JSONObject();
			result.put("linkID", linkID);
			ArrayList<URIMember> member= EntityManagement.getInstance().getURIMembersOfEntity(Entity.URI_ENTITY, linkID, lang) ;
			result.put("label", member.get(0).getLabel());
			result.put("uri", member.get(0).getURI());
			result.put("entity", array);
			response.getWriter().print(result);
			
		} 
		else if (option.equals("sventity")) {
			JSONObject result = new JSONObject();
 			/**
 			 * 返回值类型：jsonobject，
 			 * 其包含status:ok,noautority,conflict,removed,memconflict
 			 * 当status==memconflict，同时返回conflictUID,conflictEntity
 			 * 当status==ok，同时返回创建或更新实体ID及其类型
 			 */
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			int groupID = Integer.parseInt((String) regtJSON.get("groupID"));
			String name = (String) regtJSON.get("name");
			int etype = Integer.parseInt((String) regtJSON.get("etype"));
			int eid = Integer.parseInt((String) regtJSON.get("eid"));
			String  comment = (String) regtJSON.get("comment");
			String lang =(String) regtJSON.get("lang");
			JSONArray array = (JSONArray)regtJSON.get("member");
			JSONArray imgAdd = (JSONArray)regtJSON.get("imgAdd");
			JSONArray imgDel = (JSONArray)regtJSON.get("imgDel");
			String userName =(String)regtJSON.get("user");
			String isCollection =(String)regtJSON.get("isCollection");
			
			//区分是实体还是集合
			int resultEntityType = Entity.CUSTOM_ENTITY;
			if(isCollection!=null){
				resultEntityType = Entity.COLLECTION;
			}
			int userID = -1;
			try {
				userID = UserNameIDCache.getInstance().getUserID(userName);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			String group = null;
			try {
				group = GroupNameIDCache.getInstance().getName(groupID);
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			boolean getAuthority = Collaboration.getInstance()
					.getEditAuthority(Collaboration.ENTITY, eid, userID);
			if (getAuthority) {
				// 同步锁
				Object groupLock = Collaboration.getInstance()
						.getGroupProductLock(Collaboration.ENTITY, groupID);

				// 判断以eid标识的自定义实体是否因协同编辑而在别处已被删除
				boolean isthere = true;
				if (eid > 0) {
					synchronized (groupLock) {
						isthere = Entity.isThere(eid);
					}
				}
				if (!isthere) {
					Collaboration.getInstance().recoverAuthority(Collaboration.ENTITY, eid);
					result.put("status", this.STATUS_REMOVE);
				} else {
					HashSet<URIResource> members = new HashSet<URIResource>();

					int initialeid = eid;
					boolean exist = false;
					boolean conflictFlag = false;
					synchronized (groupLock) {
						int conflictUID = -1;
						JSONObject conflictEntity = new JSONObject();
							// 将整个成员判断已用放在同步代码段，能够保证当前实体不在
							// 其它同组实体中出现，因为应有的成员更新也在同步代码段
							// 可能速度慢点吧，但是逻辑上保证正确
						for (int i = 0; i < array.size(); i++) {
							int id = Integer.parseInt((String) array.get(i));
							String uriStr = null;
							// 集合不需要判断成员冲突
							if (isCollection == null) {
								HashSet<Item> items = EntityManagement
										.getInstance().getRelatedMyGroupEntity(
												Entity.URI_ENTITY, id, groupID,
												null);

								if (items.size() > 1) {
									conflictFlag = true;
									conflictUID = id;
									for (Item item : items) {
										if (item.getEID() != eid) {
											conflictEntity.put("etype",
													item.getEType());
											conflictEntity.put("eid",
													item.getEID());
											conflictEntity.put("name",
													item.getName());
											break;
										}
									}
									break;
								} else if (items.size() == 1) {
									Item item = null;
									for (Item item2 : items) {
										item = item2;
									}
									if (item.getEID() != eid) {
										conflictFlag = true;
										conflictUID = id;
										conflictEntity.put("etype",
												item.getEType());
										conflictEntity
												.put("eid", item.getEID());
										conflictEntity.put("name",
												item.getName());
										break;
									}
								}
							}

							try {
								uriStr = URIIDCache.getInstance().getURI(id);
							} catch (Throwable e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							URIResource resource = ResourceFactory
									.getInstance().createURIResource(uriStr);
							members.add(resource);
						}
                       
						if (conflictFlag) {
							result.put("status", this.STATUS_MEMBER_CONFLICT);
							result.put("conflictUID", conflictUID);
							result.put("conflictEntity", conflictEntity);
							Collaboration.getInstance().recoverAuthority(
									Collaboration.ENTITY, eid);
						} else {

							if (eid > 0) {
								int entityID = Entity.getEntityIdByNameGroupIDLang(
										name, groupID, lang);
								if (entityID > 0 && entityID != eid) {
									exist = true;
								}
								// 在eid>0情况下，名字不冲突，赶紧存储名字及其成员
								// 其它entity就不能使用相同名字了和相关成员了(同组)
								if (!exist) {
									Entity.addOrUpdateLangName(eid, name,lang);
									Entity.updateMembers(eid, members);
								}

							} else {
								//临时集合的话肯定不冲突
								if (isCollection == null) {
									int entityID = Entity
											.getEntityIdByNameGroupIDLang(name,
													groupID, lang);
									if (entityID > 0) {
										exist = true;
									}
								}
								if (!exist) {
									// 在eid<=0情况下，名字不冲突，赶紧存储
									// 由于在同步代码块内，其它Entity就不能使用相同名字了
									Entity entity = null ;
									if(isCollection==null)
										entity = new CustomEntity(name, group, lang, members);
									else{
										entity = new CustomCollection(name, group, lang, members);
									}
									entity.serializeNew();
									eid = Entity.getEntityIdByNameGroupLang(name,group,lang);
								}
							}
						}
					}

					//如果member conflict 那么直接跳过这一步
					if (!conflictFlag) {
						if (!exist) {
                            //非同步代码段
							/*存储实体类型*/
							HashSet<Integer> types = new HashSet<Integer>();
							for(URIResource resource:members){
								int uid = resource.getID();
								try {
									types.addAll(URITypeCache.getInstance().getTypes(uid));
								} catch (Throwable e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							ArrayList<Integer> typeArray = new ArrayList<Integer>(types);
							Entity.storeClassTypesById(eid, typeArray);
							
							//description存储
							if (comment != null) {
								Comment comm = new Comment(group,
										System.currentTimeMillis(), lang, comment, resultEntityType,
										eid);
								comm.serialize();
							}
							
							//img存储
							if(imgAdd!=null){
								for(int i=0;i<imgAdd.size();i++){
									String imgPath =(String)imgAdd.get(i) ;
									Image image = new Image(group,System.currentTimeMillis(),imgPath,resultEntityType,eid);
									image.serialize();
								}
							}
							if(imgDel!=null){
								for(int i=0;i<imgDel.size();i++){
									int imgID =Integer.valueOf((String)imgDel.get(i));
									Image.delete(imgID);
								}
							}
							
							//用户visit日志
							EntityManagement.storeUserVisit(userName,
									resultEntityType, eid, lang);

							//收藏夹bookmark
							//查看是否已有了收藏夹
							int bmid = Bookmark.hasBookmarkOnMemberLang(userID,resultEntityType, eid,lang);
		
							if(bmid<=0){
								boolean flag = false;
								int testBMID = Bookmark.getBookmarkIdByNameAuthor(name, userName);
								if (testBMID > 0) {
									ArrayList<Integer> testArrayList = Bookmark
											.getMembersByBookmarkId(testBMID);
									if (testArrayList.size()<=0 || testArrayList.get(0) != resultEntityType
											|| testArrayList.get(1) != eid) {
										flag = true;
									}
								}
								if (flag) {
									int start = 0;
									while (true) {
										start++;
										name = name + "(" + start + ")";
										if (Bookmark.getBookmarkIdByNameAuthor(name, userName) <= 0) {
											break;
										}
									}
								}
								Bookmark bm = new Bookmark(name, userName, lang,
										resultEntityType, eid);
								bm.serializeByAuto();
							}

							//软件制品解锁
							Collaboration.getInstance().recoverAuthority(Collaboration.ENTITY, initialeid);
							
							result.put("status", this.STATUS_OK);
							result.put("entityID", eid);
							result.put("entityType", resultEntityType);
							
						} else {
							Collaboration.getInstance().recoverAuthority(
									Collaboration.ENTITY, eid);
							result.put("status", this.STATUS_CONFLICT);
						}
					}
				}
			} else {
				// 没有编辑权限，返回noauthority
				result.put("status", this.STATUS_NOAUTHORITY);
			}

			// 最终返回结果
			response.getWriter().print(result);
		}		
		else if (option.equals("hasRDFDesc")) {
			String str = URLDecoder.decode(json,"utf-8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(str);
			String uri = (String) regtJSON.get("uri");
			String lang =(String) regtJSON.get("lang");
			
			boolean flag = true;
			if (uri == null || uri.trim().equals("")) {
				flag = false;
			} else {
				uri = uri.trim();
			
				flag = EntityBrowsing.hasRDFDescription(uri);
			}

			if (!flag) {
				/* start:由于DBpedia等网站会被封掉，因此使用falcons数据集作为后备 */
				flag = EntityBrowsing.getReserveRDFDescription(uri);
				/* end:由于DBpedia等网站会被封掉，因此使用falcons数据集作为后备 */
			}
			
			JSONObject jsob = new JSONObject();
			if(!flag){
				jsob.put("flag", "invalid");
			}else{
				jsob.put("flag", "valid");
				int uriID = 0;
				try {
					uriID = URIIDCache.getInstance().getURIID(uri, false);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String label = "";
				try {
					label = URILabelCache.getInstance().getLabel(uriID, lang);
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if(label.trim().equals("")){
					label = URIUtil.getLocalname(uri);
				}
				
				jsob.put("uriID", uriID);
				jsob.put("label", label);
				jsob.put("uri", uri);
				
			    JSONArray typeArray = new JSONArray();
			    ArrayList<Entry<Integer,String>> typeArrayList = URIResource.getTypesById(uriID, lang);
			    for(Entry<Integer, String> entry:typeArrayList){
			    	JSONObject typeObject = new JSONObject();
			    	typeObject.put("id", entry.getKey());
			    	typeObject.put("label", entry.getValue()) ;
			    	typeArray.add(typeObject);
			    }
			    jsob.put("type", typeArray) ;
			}
			response.getWriter().print(jsob);
		}		
	}
}
